<template>
  <div class="material-selector">
    <el-dialog
      :title="title"
      v-model="visible"
      width="900px"  
      append-to-body
      @close="handleClose"
      destroy-on-close
    >
      <!-- 搜索条件 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
        <el-form-item label="物料编码" prop="materialCode">
          <el-input
            v-model="queryParams.materialCode"
            placeholder="请输入物料编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input
            v-model="queryParams.materialName"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="物料类型" prop="materialType">
          <el-select v-model="queryParams.materialType" placeholder="请选择物料类型" clearable>
            <el-option
              v-for="dict in material_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="dict in mwm_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格数据 -->
      <el-table 
        v-loading="loading" 
        :data="materialList" 
        @row-click="handleRowClick"
        highlight-current-row
        :row-class-name="rowClassName"
        height="400px"
        border
      >
        <el-table-column label="物料ID" align="center" prop="materialId" width="80" />
        <el-table-column label="物料编码" align="center" prop="materialCode" width="120" />
        <el-table-column label="物料名称" align="center" prop="materialName" width="150" />
        <el-table-column label="规格型号" align="center" prop="specification" width="120" />
        <el-table-column label="单位" align="center" prop="unit" width="80" />
        <el-table-column label="物料类型" align="center" prop="materialType" width="100">
          <template #default="scope">
            <dict-tag :options="material_type" :value="scope.row.materialType"/>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template #default="scope">
            <dict-tag :options="mwm_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              @click.stop="selectMaterial(scope.row)"
              :disabled="!isMaterialSelectable(scope.row)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        :pageSizes="[5, 10, 20, 30]"
        :small="true"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="confirmSelection" :disabled="!selectedMaterial">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listMaterial } from "@/api/mwm/material";
import { ref, reactive, toRefs, getCurrentInstance, defineProps, defineEmits, watch } from 'vue';

const { proxy } = getCurrentInstance();
const { material_type, mwm_status } = proxy.useDict('material_type', 'mwm_status');

// 定义属性和事件
const props = defineProps({
  title: {
    type: String,
    default: '选择物料'
  },
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:visible', 'select']);

// 数据部分
const materialList = ref([]);
const loading = ref(false);
const visible = ref(false);
const total = ref(0);
const selectedMaterial = ref(null);
const selectedRowIndex = ref(null);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    materialCode: null,
    materialName: null,
    materialType: null,
    status: null
  }
});

const { queryParams } = toRefs(data);

// 监听visible变化
watch(() => props.visible, (val) => {
  if (val) {
    // 当弹窗显示时初始化数据
    getList();
  }
  visible.value = val;
});

// 监听内部visible变化
watch(() => visible.value, (val) => {
  emit('update:visible', val);
});

// 查询物料列表
function getList() {
  loading.value = true;
  listMaterial(queryParams.value).then(response => {
    materialList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 判断物料是否可选
function isMaterialSelectable(material) {
  // 通常只有启用状态的物料可选
  return material.status === '1' || material.status === 1;
}

// 行样式
function rowClassName({row, rowIndex}) {
  let classNames = '';
  
  // 选中行高亮
  if (selectedRowIndex.value === rowIndex) {
    classNames += 'row-selected ';
  }
  
  // 不可选择的物料行样式
  if (!isMaterialSelectable(row)) {
    classNames += 'row-disabled';
  }
  
  return classNames;
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 行点击事件
function handleRowClick(row, column, event) {
  // 只有可选择的物料才能被选中
  if (isMaterialSelectable(row)) {
    selectedMaterial.value = row;
    selectedRowIndex.value = materialList.value.findIndex(item => item.materialId === row.materialId);
  } else {
    // 提示用户该物料不可选择
    proxy.$modal.msgWarning(`该物料当前不可用，请选择启用状态的物料`);
  }
}

// 选择物料
function selectMaterial(row) {
  if (isMaterialSelectable(row)) {
    selectedMaterial.value = row;
    selectedRowIndex.value = materialList.value.findIndex(item => item.materialId === row.materialId);
  }
}

// 确认选择
function confirmSelection() {
  if (selectedMaterial.value) {
    emit('select', selectedMaterial.value);
    handleClose();
  }
}

// 关闭对话框
function handleClose() {
  emit('update:visible', false);
  selectedMaterial.value = null;
  selectedRowIndex.value = null;
}

// 打开方法，由父组件调用
function open() {
  visible.value = true;
  reset();
  getList();
}

// 重置方法
function reset() {
  queryParams.value.materialCode = null;
  queryParams.value.materialName = null;
  queryParams.value.materialType = null;
  queryParams.value.status = null;
  queryParams.value.pageNum = 1;
  selectedMaterial.value = null;
  selectedRowIndex.value = null;
}

// 对外暴露方法
defineExpose({
  open
});
</script>

<style scoped>
.material-selector .row-selected {
  background-color: #f0f9eb !important;
}

.material-selector .row-disabled {
  background-color: #f9f9f9 !important;
  color: #999 !important;
  cursor: not-allowed !important;
}

.material-selector .el-table {
  margin-top: 10px;
  margin-bottom: 10px;
}

.material-selector .pagination-container {
  margin-top: 10px;
}
</style> 